package jdo.crud;


import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.*;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import jdo.entity.Tramway;
import jdo.pmf.PMF;

/**
 * Servlet implementation class TramwayCRUD
 */
@SuppressWarnings("serial")
public class TramwayCRUD extends HttpServlet {

	@SuppressWarnings("unchecked")
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("text/html");
		//response.setHeader("Cache-Control", "no-store"); // HTTP 1.1
		//response.setHeader("Pragma", "no-cache"); // HTTP 1.0
		//response.setDateHeader("Expires", 0); // prevents caching at the proxy server
		PrintWriter page = response.getWriter();
		String pageURL = request.getRequestURI();
		page.print("<body>");
		page.print("<h1>Basic CRUD actions with JPO in Google App Engine</h1>");
		Tramway tramway = null;
		PersistenceManager pm = PMF.getPersistenceManager();
		try {
			if (request.getParameterMap().containsKey("Tramwayid_tram")) {
				// Find a record given it's key
				long id_tram = Long.parseLong(request.getParameter("Tramwayid_tram"));
				tramway = pm.getObjectById(Tramway.class, id_tram);
			}

			String action = request.getParameter("action");
			if ("CREATE".equals(action)) {
				//pm.currentTransaction().begin();
				String name = request.getParameter("name");
				// Create a record
				tramway = new Tramway(name,null,null);
				pm.makePersistent(tramway);
				tramway = null;
				//pm.currentTransaction().commit();
				// Key will be initialized automagically
				page.print("Tramway " + name + " created. <a href=" + pageURL + ">continue...</a>");
			} else if ("DELETE".equals(action)) {
				//pm.currentTransaction().begin();
				String name = tramway.getNom();
				// delete a record
				pm.deletePersistent(tramway);
				tramway = null;
				//pm.currentTransaction().commit();
				page.print("Tramway " + name + " deleted. <a href=" + pageURL + ">continue...</a>");
			} else if ("UPDATE".equals(action)) {
				// update a record
				tramway.setNom(request.getParameter("name"));
				// Changes will be stored automagically when pm
				// is closed
				page.print("Tramway " + tramway.getNom() + " updated. <a href=" + pageURL + ">continue...</a>");
				tramway = null;

			} 
				// Iterate through all entity record
				Query query;
				List<Tramway> results;
				if ("FILTER".equals(action)) {
					tramway = null;
					String queryText = "SELECT FROM isis.cloud.jdo.entity.Tramway "
							+ "WHERE this.lastName.startsWith(:filter)";
					String filter = request.getParameter("lastName");
					// query.setFilter(":p == lastName");
					// query.declareParameters("String lastNameParam");
					query = pm.newQuery(queryText);
					results = (List<Tramway>) query.execute(filter);
				} else {
					String queryText = "SELECT FROM isis.cloud.jdo.entity.Tramway ";
					query = pm.newQuery(queryText);
					results = (List<Tramway>) query.execute();
				}
				//Extent<Tramway> extent = pm.getExtent(Tramway.class, false);
				page.print("<h2>Saved Entities</h2>");
				page.print("<table border=1><tr><th>ID</th><th>FirstName</th><th>LastName</th><th>HireDate</th><th>Action</th></tr>");
				for (Tramway record : results) {
					long id_tram = record.getKey();
					page.print("<tr><td>" + id_tram + "</td><td>" + record.getNom() + "</td><td>"
							+ record.getCoordX() + "</td><td>" + record.getCoordY()
							+ "</td><td>" + "<a href=" + pageURL
							+ "?action=DELETE&Tramwayid_tram=" + id_tram + ">delete</a> "
							+ "<a href=" + pageURL + "?Tramwayid_tram=" + id_tram
							+ ">update</a></td></tr>");
				}
				query.closeAll();
				page.print("</table>");
				if ("FILTER".equals(action))
					page.print("<p>Filtered result, <a href=" + pageURL
							+ ">See all records</a></p>");

				// Show form and record list
				showForm(response.getWriter(), tramway);
			
		} catch (Exception except) {
			page.print("<p>Error: " + except.getMessage() + " <a href=" + pageURL + ">continue...</a></p>");
		} finally {
			pm.close();
		}
		page.print("<p><a href=..>Back to menu</a></p>");
		page.print("</body>");
	}

	void showForm(PrintWriter writer, Tramway record) {
		String nom = record != null ? record.getNom() : "";

		writer.print("<br><h2>Tramway form</h2><form>");
		writer.print("first name: <input name=firstName value='" + nom + "'><br>");
		if (record != null) {
			writer.print("Key: <input name=Tramwayid_tram readonly value='" + record.getKey() + "'><br>");
			writer.print("<input type=submit name=action value=UPDATE></form><br>");
		} else
			writer.print("<input type=submit name=action value=CREATE></form><br>");
	}
}
